package com.example.tests;

import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;

public class TestBase {

	private static WebDriver driver;
	private StringBuffer verificationErrors = new StringBuffer();

	@BeforeTest
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}
	
	@AfterTest
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	protected void createGroup(GroupObject groupObject) {
		openMainPage();
		goToGroupListPage();
		initGroupCreation();
		fillGroupForm(groupObject);
		submitGroupCreation();
		returnToListPage();
	}

	private void returnToListPage() {
		//return to group list page
		driver.findElement(By.linkText("group page")).click();
	}

	private void submitGroupCreation() {
		//submit group creation
		driver.findElement(By.name("submit")).click();
	}

	private void fillGroupForm(GroupObject groupObject) {
		//fill group form
		type("group_name", groupObject.name);
		type("group_header", groupObject.header);
		type("group_footer", groupObject.footer);
	}

	private void type(String locator, String name) {
		driver.findElement(By.name(locator)).clear();
		driver.findElement(By.name(locator)).sendKeys(name);
	}

	private void initGroupCreation() {
		//init group creation
		driver.findElement(By.name("new")).click();
	}

	private void goToGroupListPage() {
		//go to group list page
		driver.findElement(By.linkText("groups")).click();
	}

	public void openMainPage() {
		//open main page
		driver.get("http://localhost/addressbookv4.1.4/");
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

}
